import time

import upyun
import re

print("接入又拍云并获取列表")
RootPath = '/MyMusic/'
with open("GetFrontEnd/pwd", "r") as pwdfile:
    lines = pwdfile.readlines()
    service = lines[0].replace("\n", "")
    username = lines[1].replace("\n", "")
    password = lines[2].replace("\n", "")
    CDNurl = lines[3].replace("\n", "")
up = upyun.UpYun(service, username, password)
MusicDict = {}
MusicType = ["wav", "WAV", "mp3", "MP3", "FLAC", "flac", "m4a", "M4A"]
MusicUrls = {}
MusicLrcUrls = {}
MusicPicUrls = {}


def GetAllMusic():
    global MusicDict, MusicUrls, MusicPicUrls
    listres = GetList(RootPath)
    listindex = 0
    musicindex = 1
    for MusicList in listres:
        if MusicList["type"] == "F":
            listindex += 1
            listname = MusicList["name"]
            ListID = "3" + str(listindex).zfill(7)
            MusicDict[ListID] = {
                "ListName": listname,
                "ListPicUrl": CDNurl + RootPath + listname + ".png",
                "data": {}
            }
            musics = GetList(RootPath + listname)
            with open("testfile.json" , "w", encoding="utf-8") as file:
                file.write(str(musics))
            for music in musics:
                if music["name"].split(".")[-1] in MusicType:
                    musicindex += 1
                    nameres = re.split("[._]", music["name"])
                    try:
                        ar_name = nameres[1]
                    except IndexError:
                        ar_name = "?"
                    try:
                        al_name = nameres[2]
                    except IndexError:
                        al_name = "?"
                    music_id = "1" + str(musicindex).zfill(7)
                    musicdata = {
                        "music_name": nameres[0],
                        "ar_name": ar_name,
                        "al_name": al_name,
                        "al_picUrl": "/api?id=" + music_id + "&param=300y300"
                    }
                    MusicDict[ListID]["data"][music_id] = musicdata
                    MusicUrls[music_id] = CDNurl + RootPath + listname + "/" + music["name"]
                    MusicLrcUrls[music_id] = [RootPath + listname, music]
                    MusicPicUrls[music_id] = [RootPath + listname, music]
    return MusicDict


def GetList(dirpath):
    print("开始获取")
    time_start = time.time()
    try:
        listres = up.getlist(dirpath, limit=10000, order='asc', begin='')
        if listres:
            print("成功获取到%s个文件" % str(len(listres)))
    except Exception as e:
        print(type(e), e)
        listres = False
    time_end = time.time()
    print('耗时：', time_end - time_start, 's')
    return listres


def GetMusicPNG(music_id):
    path, music = MusicPicUrls[music_id]
    filename = music["name"].replace(music["name"].split(".")[-1], "") + "png"
    try:
        up.getinfo(path + "/封面/" + filename)
    except upyun.modules.exception.UpYunServiceException:
        return CDNurl + RootPath + "音乐.png"
    return CDNurl + path + "/封面/" + filename


def GetMusicLrc(path, music):
    lrcname = music["name"].replace(music["name"].split(".")[-1], "") + "lrc"
    try:
        up.getinfo(path + "/歌词/" + lrcname)
    except upyun.modules.exception.UpYunServiceException:
        return ["null", ""]
    lrc_url = CDNurl + path + "/歌词/" + lrcname
    return [lrcname, lrc_url]


GetAllMusic()
# print("假装获取")